#!/bin/bash

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印横幅
print_banner() {
    echo
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    🖥️  Web终端启动器                          ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo
}

# 打印信息
print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# 打印成功信息
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

# 打印警告信息
print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# 打印错误信息
print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 检查Python环境
check_python() {
    print_info "检查Python环境..."
    
    if command_exists python3; then
        PYTHON_CMD="python3"
    elif command_exists python; then
        # Check if python points to python3
        PYTHON_VERSION=$(python --version 2>&1)
        if [[ $PYTHON_VERSION == *"Python 3"* ]]; then
            PYTHON_CMD="python"
        else
            print_error "找到的python版本不是Python 3，请使用python3"
            exit 1
        fi
    else
        print_error "未找到Python，请先安装Python 3.7+"
        echo "💡 安装方法:"
        echo "   Ubuntu/Debian: sudo apt install python3"
        echo "   CentOS/RHEL: sudo yum install python3"
        echo "   macOS: brew install python3"
        exit 1
    fi
    
    # 检查Python版本
    PYTHON_VERSION=$($PYTHON_CMD --version 2>&1 | cut -d' ' -f2)
    print_success "Python版本: $PYTHON_VERSION"
}

# 检查Docker环境
check_docker() {
    print_info "检查Docker环境..."
    
    if ! command_exists docker; then
        print_error "Docker未安装"
        echo "💡 安装方法:"
        echo "   Ubuntu: sudo apt install docker.io"
        echo "   CentOS: sudo yum install docker"
        echo "   macOS: brew install docker"
        exit 1
    fi
    
    # 检查Docker是否运行
    if ! docker version >/dev/null 2>&1; then
        print_error "Docker未运行或权限不足"
        echo "💡 解决方法:"
        echo "   启动Docker: sudo systemctl start docker"
        echo "   添加用户到docker组: sudo usermod -aG docker $USER"
        exit 1
    fi
    
    print_success "Docker环境正常"
}

# 检查Docker Compose
check_docker_compose() {
    if command_exists docker-compose; then
        COMPOSE_CMD="docker-compose"
    elif docker compose version >/dev/null 2>&1; then
        COMPOSE_CMD="docker compose"
    else
        print_error "Docker Compose未安装"
        echo "💡 安装方法:"
        echo "   pip install docker-compose"
        echo "   或使用包管理器安装"
        exit 1
    fi
}

# 检查文件
check_files() {
    if [ ! -f "server.py" ]; then
        print_error "未找到server.py文件"
        print_info "请确保在web-terminal目录下运行此脚本"
        exit 1
    fi
}

# 管理Linux容器
manage_container() {
    print_info "检查Linux容器状态..."
    
    # 检查容器是否存在
    if ! docker ps -a --filter "name=linux-basic" --format "table {{.Names}}\t{{.Status}}" | grep -q "linux-basic"; then
        print_warning "未找到linux-basic容器"
        print_info "正在创建并启动容器..."
        
        cd .. || exit 1
        $COMPOSE_CMD up -d
        if [ $? -ne 0 ]; then
            print_error "容器启动失败"
            exit 1
        fi
        cd web-terminal || exit 1
        print_success "容器启动成功"
    else
        # 检查容器是否运行
        if ! docker ps --filter "name=linux-basic" --format "table {{.Names}}\t{{.Status}}" | grep -q "linux-basic"; then
            print_info "正在启动已存在的容器..."
            docker start linux-basic
            if [ $? -ne 0 ]; then
                print_error "容器启动失败"
                exit 1
            fi
            print_success "容器启动成功"
        else
            print_success "容器已在运行"
        fi
    fi
}

# 显示连接信息
show_connection_info() {
    echo
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                      🔗 连接信息                              ║"
    echo "║                                                              ║"
    echo "║  🌐 Web终端地址: http://localhost:8081                       ║"
    echo "║  🐧 Linux容器地址: localhost:2222                            ║"
    echo "║                                                              ║"
    echo "║  👤 登录账户:                                                 ║"
    echo "║     用户名: developer                                        ║"
    echo "║     密码: dev123                                             ║"
    echo "║                                                              ║"
    echo "║  🎯 使用方法:                                                 ║"
    echo "║     1. 在浏览器中打开: http://localhost:8081                  ║"
    echo "║     2. 点击\"🔗 连接SSH\"按钮                                   ║"
    echo "║     3. 输入密码: dev123                                       ║"
    echo "║     4. 开始使用Linux命令行                                    ║"
    echo "║                                                              ║"
    echo "║  ⌨️  快捷键:                                                  ║"
    echo "║     Ctrl+C - 停止服务器                                       ║"
    echo "║                                                              ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo
}

# 打开浏览器
open_browser() {
    print_info "3秒后自动打开浏览器..."
    
    # 后台延迟打开浏览器
    (
        sleep 3
        if command_exists xdg-open; then
            xdg-open "http://localhost:8081" >/dev/null 2>&1
        elif command_exists open; then
            open "http://localhost:8081" >/dev/null 2>&1
        elif command_exists firefox; then
            firefox "http://localhost:8081" >/dev/null 2>&1 &
        elif command_exists google-chrome; then
            google-chrome "http://localhost:8081" >/dev/null 2>&1 &
        elif command_exists chromium-browser; then
            chromium-browser "http://localhost:8081" >/dev/null 2>&1 &
        fi
    ) &
}

# 启动Web服务器
start_server() {
    print_info "启动Web终端服务器..."
    echo
    
    # 捕获Ctrl+C信号
    trap 'echo; print_info "正在停止服务器..."; exit 0' INT
    
    # 启动Python服务器
    $PYTHON_CMD server.py
}

# 主函数
main() {
    print_banner
    
    # 检查环境
    check_python
    check_docker
    check_docker_compose
    check_files
    
    # 管理容器
    manage_container
    
    # 等待容器完全启动
    print_info "等待容器完全启动..."
    sleep 3
    
    # 显示信息
    show_connection_info
    
    # 打开浏览器
    open_browser
    
    # 启动服务器
    start_server
}

# 运行主函数
main "$@"